package com.bw.finance.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.bw.finance.auth.UserInfo;
import com.bw.finance.conf.ResponseResult;
import com.bw.finance.eneity.TbUser;
import com.bw.finance.eneity.res.TbUserRes;
import com.bw.finance.service.ITbUserService;
import com.bw.finance.utils.ExcelUtil;
import com.bw.finance.utils.MD5Utils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.excelutils.ExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lizhengqian
 * @since 2020-05-09
 */
@RestController
@RequestMapping("/user")
public class TbUserController {
    @Autowired
    private ITbUserService service;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    private static final Logger log= LoggerFactory.getLogger(TbUserController.class);

    @Value("${filePath}")
    private String filePath;

    @PostMapping("/login")
    public ResponseResult login(@RequestBody TbUser user, HttpServletResponse response){
        log.info("用户登录开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            user.setPwd(MD5Utils.md5Encrypt32Lower(user.getPwd()));
            QueryWrapper<TbUser> queryWrapper=new QueryWrapper();
            queryWrapper.lambda().eq(TbUser::getUserName,user.getUserName())
                    .eq(TbUser::getPwd,user.getPwd());
            TbUser us = service.getOne(queryWrapper);
            if(us!=null){
                UserInfo userInfo = new UserInfo(us.getId(), us.getFullName());
                String token= UUID.randomUUID().toString();
                Cookie cookie = new Cookie("token",token);
                cookie.setMaxAge(1800*30);
                cookie.setPath("/");
                response.addCookie(cookie);
                redisTemplate.opsForValue().set(token,userInfo);
                redisTemplate.expire(token,30, TimeUnit.MINUTES);
                Map mapinfo=new HashMap();
                mapinfo.put("user",us);
                mapinfo.put("token",token);
                result.setResult(mapinfo);
                result.setMessage("登录成功");
            }else{
                result.setMessage("用户或密码错误");
                result.setSuccess(false);
            }
        }catch (Exception e){
            log.error("用户登录异常"+e.toString());
            result.setSuccess(false);
            result.setMessage("用户登录异常"+e.toString());
        }
        log.info("用户登录结束");
        return result;
    }

    @PostMapping("/list/{pagenum}/{pagesize}")
    public ResponseResult list(@PathVariable Integer pagenum, @PathVariable Integer pagesize, @RequestBody TbUserRes tbUserRes){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            if(tbUserRes.getFullName()!=null&&!"".equals(tbUserRes.getFullName())){
                queryWrapper.like("FULL_NAME","%"+tbUserRes.getFullName()+"%");
            }
            if(null!=tbUserRes.getStartDate()&&null!=tbUserRes.getEndDate()){
                queryWrapper.between("HIREDATE",tbUserRes.getStartDate(),tbUserRes.getEndDate());
            }
            PageHelper.startPage(pagenum,pagesize);
            List<TbUser> list = service.list(queryWrapper);
            PageInfo pageInfo = new PageInfo(list);
            result.setResult(pageInfo);
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("查询失败"+e.toString());
        }
        return result;
    }
   @PostMapping("/saveuser")
    public ResponseResult saveuser(@RequestBody TbUser tbUser){
       ResponseResult result = ResponseResult.SUCCESS();
       try {
           QueryWrapper queryWrapper = new QueryWrapper();
           queryWrapper.eq("USER_NAME",tbUser.getUserName());
           List<TbUser> list = service.list(queryWrapper);
           if(list.size()>0&&null==tbUser.getId()){//如果查询用户名存在则提示用户
               result.setSuccess(false);
               result.setMessage("保存失败:用户名已存在");
               return result;
           }
           tbUser.setPwd("123456");
           tbUser.setIsEnable(0);
           service.saveOrUpdate(tbUser);
           result.setMessage("保存成功");
       }catch (Exception e){
           result.setSuccess(false);
           result.setMessage("查询失败"+e.toString());
       }
       return result;
   }
    @GetMapping("/getuser/{id}")
    public ResponseResult getuser(@PathVariable Long id){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            TbUser tbUser = service.getById(id);
            result.setResult(tbUser);
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("获取失败"+e.toString());
        }
        return result;
    }
    @PostMapping("/updateisenable")
    public ResponseResult updateisenable(@RequestBody TbUser tbUser) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            service.saveOrUpdate(tbUser);
            result.setMessage("修改成功");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("修改失败" + e.toString());
        }
        return result;
    }
    @PostMapping("/upload")
    public ResponseResult upload(MultipartFile file){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
            String url=filePath;
            String path= UUID.randomUUID()+ext;
            File mfile = new File(url+path);
            file.transferTo(mfile);
            Map map=new HashMap();
            map.put("path",path);
            result.setResult(map);
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("上传异常"+e.toString());
        }
        return result;
    }
    @GetMapping("/download/{path}")
    public ResponseResult download(@PathVariable String path,HttpServletResponse response){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            FileInputStream inputStream = new FileInputStream(filePath + path);
            byte[] b = new byte[1024];
            int len;
            while((len=inputStream.read(b))>0){
                response.getOutputStream().write(b,0,len);
            }
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("异常"+e.toString());
        }
        return result;
    }
    @PostMapping("uploadfile")
    public ResponseResult uploadfile(MultipartFile file){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            //获取文件后缀
            String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
            List<Map> mapList= ExcelUtil.readExcel(ext,file.getInputStream());
            String jsonStr = JSON.toJSONString(mapList);
            List<TbUser> tbUsers=JSON.parseArray(jsonStr,TbUser.class);
            service.saveBatch(tbUsers);
            System.out.println(mapList);
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("解析失败"+e.toString());
        }
        return result;
    }
    @GetMapping("outuser")
    public void outUser(HttpServletResponse response) throws Exception {
        log.info("用户导出开始");
        //获取列表数据信息
        List<TbUser> list = service.list();
        //Excel的模板
        ClassPathResource classPathResource=new ClassPathResource("xls/user.xls");
        //Excel模板的输入流获取
        InputStream inputStream = classPathResource.getInputStream();
        response.setHeader("Content-Type","application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename="+new String("用户数据".getBytes(), "iso8859-1")+".xls");
        ExcelUtils.addValue("list",list);
        ExcelUtils.export(inputStream, ExcelUtils.getContext(),response.getOutputStream());
        log.info("用户导出结束");
    }
}

